<template>
  <div class="p-0 m-0">
    <n-form
      ref="loginFormRef"
      :model="form"
      :rules="rules"
      label-placement="left"
      label-width="80"
      require-mark-placement="right-hanging"
    >
      <n-form-item label="登录ID" path="loginId">
        <n-input v-model:value="form.loginId" placeholder="请输入登录ID" clearable size="medium" />
      </n-form-item>

      <n-form-item label="登录密钥" path="loginKey">
        <n-input
          v-model:value="form.loginKey"
          type="password"
          placeholder="请输入登录密钥"
          show-password-on="click"
          clearable
          size="medium"
        />
      </n-form-item>

      <n-form-item :show-label="false">
        <div class="flex gap-4 w-full mt-2">
          <n-button type="error" class="flex-1" @click="openCardPage"> 充值续费 </n-button>
          <n-button type="primary" :loading="loading" class="flex-1" @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </n-button>
        </div>
      </n-form-item>
    </n-form>

    <n-alert v-if="error" :title="error" type="error" :closable="false" class="mt-4" />
    <n-alert
      v-if="successMessage"
      :title="successMessage"
      type="success"
      closable
      class="mt-4"
      @close="successMessage = ''"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, watch, ref, onMounted } from 'vue'
import { NForm, NFormItem, NInput, NButton, NAlert, type FormInst, type FormRules } from 'naive-ui'
import frontendLogger from '../utils/logger'

interface FormData {
  loginId: string
  loginKey: string
}

interface LoginConfig {
  loginId?: string
  loginKey?: string
  rememberCredentials?: boolean
}

interface Props {
  modelValue?: FormData
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({
    loginId: '',
    loginKey: ''
  })
})

const emit = defineEmits<{
  'update:modelValue': [value: FormData]
  'login-success': []
  'login-start': []
  'login-end': []
  'login-log': [log: { message: string; type: string }]
}>()

const loginFormRef = ref<FormInst | null>(null)
const loading = ref(false)
const error = ref('')
const successMessage = ref('')

// 表单数据
const form = reactive<FormData>({
  loginId: '',
  loginKey: ''
})

// 表单验证规则
const rules: FormRules = {
  loginId: [{ required: true, message: '请输入登录ID', trigger: 'blur' }],
  loginKey: [{ required: true, message: '请输入登录密钥', trigger: 'blur' }]
}

// 监听props变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      form.loginId = newVal.loginId || ''
      form.loginKey = newVal.loginKey || ''
    }
  },
  { immediate: true, deep: true }
)

// 监听form变化
watch(
  form,
  (newVal) => {
    emit('update:modelValue', { ...newVal })
  },
  { deep: true }
)

// 登录处理
const handleLogin = async (): Promise<void> => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
  } catch {
    return
  }

  loading.value = true
  error.value = ''
  successMessage.value = ''

  // 通知父组件开始登录
  emit('login-start')
  sendLog('开始登录验证...', 'info')

  try {
    sendLog(`正在验证用户凭据: ${form.loginId}`, 'info')
    const result = await window.api.login(form.loginId, form.loginKey)

    if (result.success) {
      sendLog('VIP验证成功', 'success')
      // 登录成功后保存凭据
      await saveCredentials(form.loginId, form.loginKey, true)
      sendLog('登录凭据已保存', 'success')
      successMessage.value = '登录成功！'
      error.value = ''

      // 延迟一下再触发登录成功事件，让用户看到成功提示
      setTimeout(() => {
        emit('login-success')
      }, 1000)
    } else {
      sendLog(`登录失败: ${result.message || '请检查用户名和密码'}`, 'error')
      error.value = result.message || '登录失败，请检查用户名和密码'
    }
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : '未知错误'
    sendLog(`登录过程中发生错误: ${message}`, 'error')
    error.value = '登录过程中发生错误，请稍后重试'
    frontendLogger.error(`登录错误: ${message}`)
  } finally {
    loading.value = false
    sendLog('登录验证完成', 'info')
    // 通知父组件登录结束
    emit('login-end')
  }
}

// 保存登录凭据
const saveCredentials = async (
  loginId: string,
  loginKey: string,
  remember = true
): Promise<void> => {
  try {
    await window.api.saveAppConfig('login', {
      loginId,
      loginKey: remember ? loginKey : '',
      rememberCredentials: remember
    })
    frontendLogger.success('登录凭据已保存')
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : '未知错误'
    frontendLogger.error(`保存登录凭据失败: ${message}`)
  }
}

// 加载保存的登录凭据
const loadSavedCredentials = async (): Promise<void> => {
  try {
    const loginConfig = (await window.api.getAppConfig('login')) as LoginConfig
    if (loginConfig && loginConfig.loginId && loginConfig.rememberCredentials) {
      form.loginId = loginConfig.loginId
      if (loginConfig.loginKey) {
        form.loginKey = loginConfig.loginKey
      }
      frontendLogger.info('已加载保存的登录凭据')
    }
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : '未知错误'
    frontendLogger.error(`加载保存的登录凭据失败: ${message}`)
  }
}

// 清除成功消息
const clearSuccessMessage = (): void => {
  successMessage.value = ''
}

// 发送日志到父组件
const sendLog = (message: string, type = 'info'): void => {
  emit('login-log', { message, type })
}

// 暴露方法给父组件
defineExpose({
  clearSuccessMessage
})

// 打开获取卡密页面
const openCardPage = (): void => {
  try {
    // 降级方案：使用原生方法
    window.open(
      'https://env-00jxu65bfie3-static.normal.cloudstatic.cn/admin/index.html#/',
      '_blank'
    )
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : '未知错误'
    frontendLogger.error(`打开浏览器失败: ${message}`)
  }
}

// 自动登录功能
const autoLogin = async (): Promise<void> => {
  try {
    const loginConfig = (await window.api.getAppConfig('login')) as LoginConfig
    if (
      loginConfig &&
      loginConfig.loginId &&
      loginConfig.loginKey &&
      loginConfig.rememberCredentials
    ) {
      sendLog('检测到保存的登录凭据，开始自动登录...', 'info')
      form.loginId = loginConfig.loginId
      form.loginKey = loginConfig.loginKey

      // 延迟一下再自动登录，确保UI已渲染
      setTimeout(async () => {
        await handleLogin()
      }, 500)
    } else {
      sendLog('未找到保存的登录凭据，等待用户手动登录', 'info')
    }
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : '未知错误'
    sendLog(`自动登录失败: ${message}`, 'error')
    frontendLogger.error(`自动登录失败: ${message}`)
  }
}

// 组件挂载时加载保存的凭据并尝试自动登录
onMounted(async () => {
  await loadSavedCredentials()
  await autoLogin()
})
</script>
